/**
 * <copyright>
 * </copyright>
 *
 * $Id$
 */
package Wires.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.gmt.tcs.extractor.TCSExtractor;
import org.eclipse.m2m.atl.engine.AtlEMFModelHandler;
import org.eclipse.m2m.atl.engine.extractors.Extractor;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMModel;
import org.eclipse.m2m.atl.engine.vm.nativelib.ASMString;

import Wires.ConnectableElement;
import Wires.InputActualParameter;
import Wires.Model2TextTransformation;
import Wires.OutputActualParameter;
import Wires.WiresPackage;
import Wires.exep.ResourceNotFoundException;
import Wires.exep.TCSExtractionFailedException;
import Wires.exep.TypeNotFoundException;

/**
 * <!-- begin-user-doc -->
 * An implementation of the model object '<em><b>Model2 Text Transformation</b></em>'.
 * <!-- end-user-doc -->
 * <p>
 * </p>
 *
 * @generated
 */
public class Model2TextTransformationImpl extends QueryImpl implements Model2TextTransformation {
	/***************************************************/
	/***************** Modifications *******************/
	
//	private static int temp = 0; 
	
	public void execute(ConnectableElement incoming) throws Exception{
		List<InputActualParameter> inparam = this.getInParams();
		
		boolean ready = true;
		for (InputActualParameter parameter : inparam){
			ready = ready && ((InputActualParameterImpl)parameter).getActive();
		}
		
		if (super.getActive() == true && ready){			
			if (this.getType() == null)
				throw new TypeNotFoundException(this);
			
			String ecorePath = this.getType().getPath();
			
			File f = new File(ecorePath);			
			if (this.getType().getPath() == null || this.getType().getPath().equals("") || !f.exists())
				throw new ResourceNotFoundException(this.getType());
			
			ASMModel inModel = ((InputActualParameterImpl)inparam.get(0)).getModel();
			
			try{
				Extractor ext;
				HashMap<Object,Object> params;
				
//				URL TCS = getClass().getResource("/extractATL/TCS.ecore");
//				URL ecoreURL = f.toURI().toURL();
				
				String TCSPath = null;
				URI TCSURI = null;
				try{
					URL bundleRoot = Platform.getBundle("Wires").getEntry("/extractATL/TCS.ecore");  
					URL fileURL = FileLocator.toFileURL(bundleRoot);
					TCSPath = fileURL.getPath();
					TCSPath = TCSPath.substring(1);
				}catch(Exception e){
					TCSURI = URI.createURI(getClass().getResource("/extractATL/TCS.ecore").toURI().toString());
				}
				
								
				AtlEMFModelHandler emfamh = (AtlEMFModelHandler) AtlEMFModelHandler.getDefault(AtlEMFModelHandler.AMH_EMF);
				ASMModel tcsEMFmm = null;
				if (TCSPath != null)
					tcsEMFmm = emfamh.loadModel("TCS", emfamh.getMof(), URI.createFileURI(TCSPath));
				else
					tcsEMFmm = emfamh.loadModel("TCS", emfamh.getMof(), TCSURI);
				ASMModel ecoreTcsEMFmm = emfamh.loadModel("ecore.tcs", tcsEMFmm, URI.createFileURI(f.getAbsolutePath()));
				
				
				
				ext = new TCSExtractor();
				params = new HashMap<Object,Object>();

//				Map x = ext.getParameterTypes();
				
				//Initializing parameters
				params.put("format", ecoreTcsEMFmm);
				params.put("identEsc", "");
				params.put("indentString", "\t");
				params.put("serializeComments", true);
				
//				Model2TextTransformationImpl.temp++;
				String tempName = "extTemp" + UUID.randomUUID().toString() + ecoreTcsEMFmm.getName();
				
				OutputStream out = null;
				out = new FileOutputStream(tempName);					
				ext.extract(inModel, out, params);
				
				out.close();				
				
				File fich = new File(tempName);
				BufferedReader br = new BufferedReader(new FileReader(fich));
				String res="";
				String linea = br.readLine();
				while (linea!=null){					
					res+= '\n' + linea;
					linea = br.readLine();
				}
				
				br.close();
				fich.delete();		
				
				((OutputActualParameterImpl)this.getOutParams().get(0)).basicDataValue = new ASMString(res);				
			}catch(Exception e){
				throw new TCSExtractionFailedException(this);
			}
			
			//Get the output parameters
			List<ConnectableElement> outParamlist = new LinkedList<ConnectableElement>();
			for (OutputActualParameter oap : this.getOutParams()){
				outParamlist.add(((ConnectableElement)oap));
			}
			
			for (InputActualParameter iap : this.getInParams()){
				((InputActualParameterImpl) iap).setActive(false);
			}
			
			if (this.getControlNode()!=null)
				super.setActive(false);
			
			//Call the main method from WiresSpecification
			WiresSpecificationImpl.execute(outParamlist, null);
		}
	}
		
	/**************** Modifications End ****************/
	/***************************************************/
	
	
	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	protected Model2TextTransformationImpl() {
		super();
	}

	/**
	 * <!-- begin-user-doc -->
	 * <!-- end-user-doc -->
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return WiresPackage.Literals.MODEL2_TEXT_TRANSFORMATION;
	}

} //Model2TextTransformationImpl
